package com.channel.demo;

import java.io.*;

/**
 * Created by Liu on 2017/11/23.
 */
public class ChannelImpl implements Ichannel {

    @Override
    public void WriteChannel(File in, File out) {
        if (!in.exists()) {
            throw new RuntimeException("请输入正确的路径，thank you!");
        }
        File parent = out.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        if (!out.exists()){
            try {
                out.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            String tempString;
            String targetString;
            boolean flag = false;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(in)));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out),"UTF-8"));
            int line = 1;
            int count = 0;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = bufferedReader.readLine()) != null) {
                if (flag) {
                    int i = tempString.indexOf("--");
                    if (i > 0) {
                        //需要裁剪
                        tempString = tempString.substring(0, i);
                    }
                    bufferedWriter.write("UMENG_CHANNEL 渠道"+tempString.trim()+" "+tempString.trim()+"\r\n");
                    System.out.println("写入渠道号---------- " + tempString);
                    count++;
                    bufferedWriter.flush();
                }
                // 显示行号
                if (tempString.startsWith("##")) {
                    flag = true;
                    System.out.println("开始写入渠道号----------开始行数： " + line);
                }
                line++;
            }
            System.out.println("渠道号总数----------" + count);
            bufferedReader.close();
            bufferedWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
